"use client"

import { useState, useEffect } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Loader2, FileSpreadsheet, ArrowLeft } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent } from "@/components/ui/card"
import { canEditByRole, getPermissionDescription } from '@/lib/data-entry-permissions'
import ParameterTable from '@/components/parameter-table'

export default function InstrumentationParametersPage() {
  const [loading, setLoading] = useState(true)
  const [fetchError, setFetchError] = useState<string | null>(null)
  const [parameters, setParameters] = useState<any[]>([])
  const [measurementUnitMap, setMeasurementUnitMap] = useState<Record<string, string>>({})
  const [currentUserRole, setCurrentUserRole] = useState('admin') // 临时写死，后续从用户系统获取
  const [isEditing, setIsEditing] = useState(false)
  const { toast } = useToast()
  const router = useRouter()
  const searchParams = useSearchParams()

  // 从URL参数获取设备信息
  const deviceId = searchParams.get('deviceId') || 'IN-0001'
  const parameterType = searchParams.get('type') || 'naming'

  // 新增：从URL参数获取设备名称、表名、code
  const deviceName = searchParams.get('deviceName') || deviceId;
  const tableName = searchParams.get('name') || '';
  const code = searchParams.get('code') || '';
  const type = parameterType;

  useEffect(() => {
    loadData()
  }, [deviceId, parameterType])

  const loadData = async () => {
    try {
      console.log('开始加载数据...')
      setLoading(true)
      setFetchError(null)

      console.log('加载计量单位映射...')
      // 加载计量单位映射
      const unitsRes = await fetch('/api/measurement-units')
      const unitsData = await unitsRes.json()
      const unitMap: Record<string, string> = {}
      unitsData.forEach((unit: any) => {
        unitMap[unit.unit_class] = unit.unit_symbol || unit.unit_name
      })
      setMeasurementUnitMap(unitMap)
      console.log('计量单位映射加载完成:', unitMap)

      // 加载参数数据 - 使用正确的参数名
      const apiUrl = `/api/sqlite-parameters?deviceId=${deviceId}&type=${parameterType}`
      console.log('准备调用参数API:', apiUrl)
      const paramsRes = await fetch(apiUrl)
      console.log('参数API响应状态:', paramsRes.status, paramsRes.ok)
      if (!paramsRes.ok) {
        throw new Error(`API返回错误: ${paramsRes.status}`)
      }
      const paramsData = await paramsRes.json()
      console.log('参数数据加载完成:', paramsData)
      setParameters(paramsData)
    } catch (error) {
      console.error('加载数据失败:', error)
      setFetchError(`加载数据失败: ${error instanceof Error ? error.message : String(error)}`)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async (updatedParameters: any[]) => {
    try {
      const response = await fetch('/api/sqlite-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId: deviceId,
          parameters: updatedParameters,
          measurementUnitMap
        }),
      })

      if (!response.ok) {
        throw new Error('保存失败')
      }

      await loadData() // 重新加载数据
    } catch (error) {
      console.error('保存失败:', error)
      throw error
    }
  }

  return (
    <div className="container mx-auto py-6">
      <div className="mb-4">
        <Button
          variant="outline"
          size="sm"
          onClick={() => {
            // 尝试返回上一页，如果失败则跳转到仪表专业页面
            try {
              if (window.history.length > 1) {
                router.back()
              } else {
                router.push('/instrumentation')
              }
            } catch (error) {
              console.error('路由跳转失败:', error)
              router.push('/instrumentation')
            }
          }}
        >
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回设备列表
        </Button>
      </div>
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold">
          {deviceName}
          {'_'}
          {type === 'naming' ? '对象命名表' : (type === 'position' || type === 'location') ? '位置信息表' : '基础参数表'}
          {'_'}
          {(() => {
            const match = tableName.match(/表\s*C\.(\d+)/);
            if (match) return `C${match[1]}`;
            if (code) return `C${code.replace(/表|\.|\s/g, '')}`;
            return '';
          })()}
        </h2>
        <div className="flex items-center gap-4">
          {!isEditing && (
            <Button
              variant="outline"
              size="sm"
              className="edit-save-button"
              onClick={() => setIsEditing(true)}
            >
              编辑
            </Button>
          )}
          {isEditing && (
            <>
              <Button
                variant="default"
                size="sm"
                className="edit-save-button"
                onClick={async () => {
                  try {
                    await handleSave(parameters);
                    setIsEditing(false);
                  } catch (error) {
                    console.error('保存失败:', error);
                  }
                }}
              >
                保存
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="cancel-button"
                onClick={() => setIsEditing(false)}
              >
                取消
              </Button>
            </>
          )}
        </div>
      </div>

      <div className="space-y-6">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
              <p className="text-muted-foreground">正在加载参数数据...</p>
            </div>
          </div>
        ) : fetchError ? (
          <div className="text-red-600 font-bold my-8">{fetchError}</div>
        ) : (
          <ParameterTable
            deviceId={deviceId}
            parameters={parameters}
            measurementUnitMap={measurementUnitMap}
            currentUserRole={currentUserRole}
            isEditing={isEditing}
            onSave={handleSave}
            onEditingChange={setIsEditing}
          />
        )}
      </div>
    </div>
  )
} 